Following are some of the commonly asked Interview questions for WebAPI.
- What is ASP.NET WebAPI
- Which protocol is supported by WebAPI?
- What are the Similarities between MVC and WebAPI
- Differences between MVC and WebAPI
- Who can consume WebAPI
- How are Requests mapped to Action methods inWebAPI
- Can the HTTP request be mapped to action method without using the HTTP attribute
- What are the new features in WebAPI 2
- What is MessageHandler
- What is Exception Filter?
What is ASP.NET Web API
WebAPI is an API which uses HTTP protocol for accessing services.It is not limited to ASP.NET and can be developed in different technologies.For developing WebAPI based services we use ASP.NET WebAPI framework.
HTTP service is a service which is build using just the HTTP protocol.
WebAPI service works with wide range of clients from browsers ,mobile apps to embedded applications.
Previously WCF was used for building web services. WCF is useful when we want to develop services which works with different protocols such as HTTP,TCP. ASP.NET Web API is useful when we want to develop services specifically using the HTTP protocol.
Which protocol is supported by WebAPI?
WebAPI supports only HTTP protocol.So it can be consumed by any client which supports HTTP protocol.
What are the Advantages of WebAPI over WCF
- WCF services or web services uses the SOAP protocol.HTTP services don’t use SOAP protocol as a result
- WebAPI services are lightweight since SOAP is not used.This reduces the data which is transferred to consume service.
- Doesn’t require much configuration : Client can interact with the service by using just the HTTP verbs.
What are the Similarities between MVC and WebAPI
- Both are based on the same principle of Separation of concerns.
- Both have similar concepts such as routing,controllers and models.
Differences between MVC and WebAPI
- MVC is used for developing applications which have User Interface.Views in MVC are used for developing user interface.
- WebAPI are used for developing HTTP services.Other applications call the WebAPI methods to fetch the data.
Who can consume WebAPI
- WebAPI can be consumed by any client which supports HTTP verbs such as: GET,PUT,DELETE,POST.
- Since WebAPI services doesn’t require any configuration they are very easy to consume by any client.
- Even portable devices such as Mobile devices can easily consume WebAPI.This is one of the biggest advantages of WebAPI.
How are Requests mapped to Action methods in WebAPI
Since WebAPI uses HTTP verbs so a client which consumes a WebAPI need some way to call the WebAPI method.
Client uses HTTP verbs to call the WebAPI action methods.For example to call a method called GetEmployee a client can use a jQuery method as:
$.get("/api/Employees/1", null, function(response) { $("#employees").html(response); });
So there is no mention of the method name above.Instead GetEmployee method is called using the GET HTTP verb.
We define the GetEmployee method as:
[HttpGet] public void GetEmployee(int id) { StudentRepository.Get(id); }
As you can see the GetEmployee method is decorated with the [HttpGet] attribute.We use different verbs to map the different HTTP requests:
- HttpGet
- HttpPost
- HttpPut
- HttpDelete
Can the HTTP request be mapped to action method without using the HTTP attribute
This is a tricky question.There are actually two ways to map the HTTP request to action method.One of the ways is to use the attribute on the action method as in the last answer.Another ways is to just name your method starting with the HTTP verb.For example if we want to define a GET method we can define it as:
public void GetEmployee(int id) { StudentRepository.Get(id); }
The above method will be automatically mapped with the GET request since it starts with GET.
What is the base class of WebAPI controllers
APIController is the base class from which all WebAPI controller derive
Giving an alias to WebAPI action method
By using the ActionName attribute.For example we are renaming the GetEmployee action method as:
[ActionName("GetSingleEmployee")] public void GetEmployee(int id) { StudentRepository.Get(id); }
What types can WebAPI action method return
WebAPI can return any of the following types:
- void This means WebAPI doesn’t returns any data.
- HttpResponseMessage This allows you to have control over the response.
- IHttpActionResult This acts as the factory for creating HttpResponseMessage.
- Custom type Any custom type.WebAPI uses different Media formatters to serialize custom type.
Can a WebPI return an HTML View?
WebAPI returns data so views are not returned from WebAPI.If you want to return views then using MVC is better idea.
How can you give a different name to action method ?
You can give a different name to action methof by using the ActionName attribute.For example if you want to rename a method called GetStudent to search then you can use the ActionName attribute as:
[ActionName("search")] public ActionResult GetStudent(int id) { // get student from the database return View(); }
What is HTTPResponseMessage
This represents the response of the WebAPI action method.It allows you to return the data along with the status code such as success or failure.
In the following example if the passed Roll Number exists in the list of students then the method returns the Student object and the status code “OK” while if the roll number doesn’t exists then “NotFound” status code is returned
public HttpResponseMessage GetStudent(int number) { Student stud = studentList.Where(student => student.rollNo == number).FirstOrDefault(); if (stud != null) { return Request.CreateResponse<Student>(HttpStatusCode.OK, stud); } else { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Student Not Found"); } }
What is routing in WebAPI
Routing in WebAPI is used for matching URLs with different routes.Routes specify which controller and action will handle the request.Routes are added to the routing table in the WebApiConfig.cs as:
routes.MapHttpRoute( name: "API Default", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } );
Routing mechanism is also used in MVC.
What are the new features in WebAPI 2
- CORS (Cross-Origin Resource Sharing)
- OWIN Hosting
- IHttpActionResult
- Attribute routing
- OWIN
- WebAPI oData
What is MessageHandler
Message handler is used to receive an HTTP request and for returning HTTP response.Message handlers are implemented as classes deriving from HttpMessageHandler.They implement the cross-cutting concerns.
How WebAPI is useful in creating RESTful web services
REST stands for ‘Representational State Transfer’.It is an architectural pattern and uses HTTP as the communication meachnism.In a REST API ,resources are the entities which are represented using
different end points.
WebAPI is used for creating RESTful web services.WebAPI controllers represents different entities in your application and different action methods are mapped using HTTP verbs such as POST and GET.
What is Exception Filter
Exception filter is executed if action method throws an unhandled exception.Exception filter implements IExceptionFilter interface.